package org.gongziqi.shiro;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.gongziqi.controller.SysLoginController;
import org.gongziqi.pojo.SysUserEntity;


public class ShiroUtils {
	
	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	public static SysUserEntity getUserEntity() {
		return (SysUserEntity)SecurityUtils.getSubject().getPrincipal();
	}

	public static Long getUserId() {
		return getUserEntity().getUserId();
	}
	
	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin() {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	public static void logout() {
		SecurityUtils.getSubject().logout();
	}
	
	public static String getKaptcha(String key) {
		
		/*io.renren.controller.SysLoginController.login(String, String, String)
		以上登录的方法，会验证图形验证码是否正确。
		而验证码是通过String kaptcha = getSessionAttribute("KAPTCHA_SESSION_KEY").toString()获取的.
		getSessionAttribute("KAPTCHA_SESSION_KEY")可能为空，就不报空指针。
		*/
		Object sessionKaptcha = getSessionAttribute(key);
		String kaptcha = sessionKaptcha == null? null: sessionKaptcha.toString();
		getSession().removeAttribute(key);
		return kaptcha;
		
		/*源代码
		 * String  kaptcha = getSessionAttribute(key).toString();
		getSession().removeAttribute(key);
		return kaptcha;*/
	}

}
